<template>
  <!--安装记录-->
  <basic-dialog v-model="dialog.showDialog" :title="dialog.title" width="1700"
                :hideFooter="true" :autoClose="false">
    <el-splitter>
      <el-splitter-panel :size="800" style="padding-right: 10px">
        <basic-crud  ref="crudRef" :option="materialOptions"
                     apiGetListUrl="/mes/workInstallItemController/listMaterial"
                     :defaultListParams="{specificationId:parentRow.specificationId,specificationTaskId:parentRow.specificationTaskId}"
                     :pageData="{pageSize:-1}"
                     :fastSearch="{name:'图号、名称',fastColumn:'code,name'}"
                     @row-click="handleRowClick">
          <template #installedQuantity="{ row }">
            <el-tag type="primary" v-if="row.installedQuantity>0">{{row.installedQuantity}}</el-tag>
            <el-tag type="info" v-else>{{row.installedQuantity}}</el-tag>
          </template>
          <template #menu="{row}">
            <el-button type="primary" text icon="plus" v-loading="addLoading" @click="addBtnClick(row)">新增</el-button>
          </template>
        </basic-crud>
      </el-splitter-panel>
      <el-splitter-panel :min="800" style="padding-left: 10px">
        <basic-crud  ref="assemblyCrudRef" :option="assemblyOptions" v-model="formData"
                     apiGetListUrl="/mes/workInstallItemController/list" :autoLoad="false"
                     :defaultListParams="{specificationTaskId:parentRow.specificationTaskId}" :pageData="{pageSize:-1}"
                     :fastSearch="{name:'批次号/编号',fastColumn:'materialRealCode'}"
                     :apiListParams="listParams"
                     :before-open="beforeOpen"
                     :row-update="rowUpdate"
                     :row-save="rowSave"
                     :row-del="removeHandler">
          <template #confirmProcessTaskId="{ row }">
            <el-tooltip v-if="row.confirmProcessTaskId != null && row.confirmProcessTaskId !=''" class="item" effect="dark"
                        :content="row.confirmCheckerName +formatDate(row.confirmDate,'yyyy-MM-dd') +
                           '在任务：' + row.confirmProcessCode + ' ' + row.confirmProcessName + ',中确认'"
                        placement="top">
              <el-tag type="primary" >已确认</el-tag>
            </el-tooltip>
          </template>
        </basic-crud>
      </el-splitter-panel>
    </el-splitter>
  </basic-dialog>
</template>

<script setup>
import {defineExpose} from "vue";
import {ElMessage} from "element-plus";
import { formatDate } from "@/utils/formatTime";
import {
  apiAddOrEditForMaterial,
  apiEditForMaterial,
  apiDelMaterial, apiCheckCanEdit
} from "@/apis/execute/processFeedback";

const dialog = ref({
  showDialog: false,
  title: "安装记录"
})

// 打开新增编辑对话框
const parentRow = ref({});
const parentOnlyShow = ref(false);
const openDialog = (row, onlyShow) => {
  dialog.value.showDialog = true;
  parentRow.value=row;
  parentOnlyShow.value=onlyShow
  materialOptions.value.menu= !onlyShow
  assemblyOptions.value.editBtn= !onlyShow
  assemblyOptions.value.delBtn= !onlyShow
  assemblyOptions.value.menu= !onlyShow
  currentRow.value=null
};
const crudRef=ref(null);
const assemblyCrudRef=ref(null);
const closeDialog=()=> {
  crudRef.value.defaultSelectList = [];
  assemblyCrudRef.value.tableData = [];
  emits('refresh-parent')
}

const currentRow=ref(null);

const materialOptions= ref({
  addBtn: false,
  editBtn:false,
  delBtn:false,
  viewBtn:false,
  align: "center",
  height: "570px",
  menu: !parentOnlyShow.value,
  menuWidth:65,
  showPage:false,
  column:[
    {
      label: "图号",
      prop: "code",
      sortable:true
    },
    {
      label: "类型",
      prop: "partType",
      width: 100,
      sortable:true
    },
    {
      label: "名称",
      prop: "name",
      sortable:true
    },
    {
      label: "需求",
      prop: "quantity",
      width: 80
    },{
      label: "已安装数量",
      prop: "installedQuantity",
      width: 90,
      slot: true,
    },
    {
      label: "单位",
      prop: "unit",
      width: 70
    },
  ]
})

const listParams=ref({})
const assemblyOptions= ref({
  addBtn: false,
  editBtn:false,
  delBtn:false,
  viewBtn:false,
  align: "center",
  height: "570px",
  menu:false,
  menuWidth: 120,
  showPage:false,
  column: [
    {
      label: "批次号/编号",
      prop: "materialRealCode",
      minWidth:160,
      rules: [
        { required: true, message: "批次号/编号不能为空" }
      ],
    },
    {
      label: "安装时间",
      prop: "installDate",
      type: "date",
      width:120,
      formatter: (row) => {
        return formatDate(row.installDate, "yyyy-MM-dd");
      },
      rules: [
        { required: true, message: "安装时间不能为空" }
      ],
    },
    {
      label: "软件版本",
      prop: "softwareRev",
      width:120,
    },
    {
      label: "数量",
      prop: "quantity",
      type: "number",
      width:70,
      rules: [
        { required: true, message: "数量不能为空" },
        { type: "number", message: "数量必须为数字值", trigger: "blur" },
      ],
    },
    {
      label: "检验确认",
      prop: "confirmProcessTaskId",
      display:false,
    },
    {
      label: "备注",
      prop: "des",
    },
  ]
})
const formData=ref({})

const handleRowClick=(row) =>{
  currentRow.value=row
  listParams.value={
    materialId:row.id
  }
}

const addBtnClick=(row)=> {
  currentRow.value=row
  assemblyCrudRef.value.crudRef.rowAdd();
}
const beforeOpen=async (done, type)=> {
  if (type === "add") {
    //看看数量。
    if(currentRow.value.installedQuantity
        && currentRow.value.installedQuantity >= currentRow.value.quantity){
      return ElMessage.error("安装数量已经足够，无需继续添加");
    }
    done();
  }else{
    const res = await  apiCheckCanEdit({id: formData.value.id});
    if(!res.success){
      return ElMessage.error(res.msg || "安装记录不可编辑");
    }
    done();
  }
}

//添加保存
const addLoading=ref(false)
const rowSave= async (form, done, loading)=> {
  let params = {};
  params.specificationTaskId = parentRow.value.specificationTaskId;
  params.materialId = currentRow.value.id;
  params.materialName = currentRow.value.name;
  params.code = currentRow.value.code;
  params.materialRev = currentRow.value.materialRev;
  params.partType = currentRow.value.partType;
  let item = {};
  item.materialRealCode = form.materialRealCode;
  item.installDate = formatDate(form.installDate,'yyyy-MM-dd');
  item.softwareRev = form.softwareRev;
  item.quantity = form.quantity;
  item.des = form.des;
  params.details = [item];

  //校验数量
  let quantity = currentRow.value.quantity;
  let installedQuantity = currentRow.value.installedQuantity;
  let _num = form.quantity;
  if((_num + installedQuantity)>quantity){
    ElMessage.warning("已超出需求数据，无需再进行安装！");
    loading()
    return false;
  }
  apiAddOrEditForMaterial(params,addLoading).then((res)=>{
    ElMessage.success("添加记录成功！");
    getRightList();
    crudRef.value.getList()
  }).finally((res) => {
    loading()
    done(form);
  });
}
//修改
const rowUpdate=(form,index,done,loading)=> {
  //校验数量
  let quantity = currentRow.value.quantity;
  let installedQuantity = currentRow.value.installedQuantity;
  let _num = form.quantity;
  if((_num + installedQuantity)>quantity ||true){
    ElMessage.warning("数量已超出需求数据！");
    loading()
    return false;
  }
  apiEditForMaterial(form).then((res)=>{
    ElMessage.success("修改成功！");
    getRightList();
  }).finally((res) => {
    loading()
    done(form);
  });
}

//删除安装记录
const removeLoading=ref(false)
const removeHandler=(row,index,done)=> {
  apiDelMaterial(row.id,removeLoading).then((res)=>{
    ElMessage.success("删除成功！");
    getRightList();
    crudRef.value.getList()
  });
}
const getRightList=()=>{
  assemblyCrudRef.value.getList()
  emits('refresh-parent')
}
defineExpose({
  openDialog
})
</script>

<style scoped>

</style>